﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Drawing;
using DevExpress.XtraGrid.Columns;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraPrinting;
using DevExpress.XtraPrintingLinks;
using DevExpress.XtraTabbedMdi;
using DevExpress.XtraEditors;
using DevExpress.XtraGrid;
using ERP_RORZE_TOOL.BizLogic;

namespace ERP_RORZE_TOOL.Common
{
    public class Utilities
    {
        public Utilities()
        {

        }

        public static bool IsNullOrEmpty(object o)
        {

            if (o != null && o.ToString() != "")
                return false;
            return true;
        }

        public static bool MessageConfirmationYesNo(string message)
        {
            bool flag = false;

            DialogResult result = MessageBox.Show(message, ToolConstants.Form.MessageBox.Confirmation, MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            if (result == DialogResult.Yes)
            {
                flag = true;
            }

            return flag;
        }

        public static void MessageErrorOk(string message)
        {
            MessageBox.Show(message, ToolConstants.Form.MessageBox.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
        }

        public class Timer
        {
            System.Windows.Forms.Timer myTimer = new System.Windows.Forms.Timer();
            public LabelControl lb = new LabelControl();

            public Timer()
            {
                myTimer.Tick += new System.EventHandler(myTimer_Tick);

            }
            public void ShowHideLabel(LabelControl label, int seconds, Color color, string text)
            {
                label.ForeColor = color;
                label.Text = text;
                label.Visible = true;
                myTimer.Interval = seconds;
                myTimer.Start();
            }

            private void myTimer_Tick(object sender, EventArgs e)
            {
                lb.Visible = false;
                myTimer.Stop();
            }

        }

        public static int CheckInput(string fieldName, string storedName, string where, bool isTempTable = false, string tempTableName = null)
        {
            int number = 0;
            ReportHelper helper = new ReportHelper();
            DataRow[] foundRows;
            if (isTempTable)
            {
                DataTable dt = helper.GetAll(storedName, tempTableName);

                foundRows = dt.Select(where);
                if (foundRows.Count() > 0)
                    try
                    {
                        number = int.Parse(foundRows[0][fieldName].ToString());
                    }
                    catch (Exception)
                    {

                        number = 0;
                    }
            }
            else
            {
                DataTable dt = helper.GetAll(storedName);

                foundRows = dt.Select(where);
                if (foundRows.Count() > 0)
                    try
                    {
                        number = int.Parse(foundRows[0][fieldName].ToString());
                    }
                    catch (Exception)
                    {

                        number = 0;
                    }
            }


            return number;
        }

        public class FormUtil
        {
            public static bool IsXtraTabOpen(XtraTabbedMdiManager xtraTabbedNeoForm, string name)
            {
                bool flag = false;
                int count = xtraTabbedNeoForm.Pages.Count;

                for (int i = 0; i < count; i++)
                {
                    if (xtraTabbedNeoForm.Pages[i].Text == name)
                    {
                        flag = true;
                    }
                }

                return flag;
            }

            public static bool IsFormOpen(Form form)
            {
                foreach (Form f in Application.OpenForms)
                    if (f.Name.Equals(form.Name) && f.Text.Equals(form.Text))
                        return true;
                return false;
            }

            public static void ActiveForm(Form form)
            {
                foreach (Form f in Application.OpenForms)
                    if (f.Name.Equals(form.Name) && f.Text.Equals(form.Text))
                    {
                        f.Activate();
                        break;
                    }
                form.Dispose();
            }

        }

        public class GridUtil
        {
            public static void SelectRow(GridView gridView, int indexRow, int action = 1)
            {
                switch (action)
                {
                    case 0:
                        gridView.UnselectRow(0);
                        gridView.SelectRow(gridView.RowCount - 1);
                        gridView.FocusedRowHandle = (gridView.RowCount - 1);
                        break;
                    case 1:
                        gridView.UnselectRow(0);
                        gridView.SelectRow(indexRow);
                        gridView.FocusedRowHandle = indexRow;
                        break;
                    case 2:
                        gridView.SelectRow(0);
                        gridView.FocusedRowHandle = (0);
                        break;

                    //action
                    // 0: addnew; 1: update; 2: delete
                }
            }
        }

        public static void CreateLogFile(string fileName, string message)
        {
            FileStream fs;
            StreamReader reader;
            string tempfile = Path.GetTempFileName();
            StreamWriter writer = new StreamWriter(tempfile);

            if (File.Exists(fileName))
            {
                reader = new StreamReader(fileName);
                writer.WriteLine(string.Format("{0} :: {1}", DateTime.Now.ToString(), message));
                while (!reader.EndOfStream)
                    writer.WriteLine(reader.ReadLine());
                writer.Close();
                reader.Close();
                File.Copy(tempfile, fileName, true);
            }
            else
            {
                using (fs = new FileStream(fileName, FileMode.OpenOrCreate))
                {
                    writer = new StreamWriter(fs);
                    writer.WriteLine(string.Format("{0} :: {1}", DateTime.Now.ToString(), message));
                    writer.Close();
                }
            }
        }

        public static void ExportToExcel(GridView gridView, int type, bool openNow)
        {
            if (gridView == null) return;

            //First: Change gridView's property PrintSelectedRowOnly to True
            gridView.OptionsPrint.PrintSelectedRowsOnly = true;
            gridView.OptionsSelection.MultiSelect = true;
            switch (type)
            {
                //0: Export selected rows
                case 0:
                    if (gridView.RowCount > 0)
                    {
                        try
                        {
                            bool success = false;
                            XlsxExportOptions option = new XlsxExportOptions();
                            option.ShowGridLines = true;
                            option.SheetName = gridView.ViewCaption;
                            //option.TextExportMode = te

                            FileDialog fileDialog = new SaveFileDialog();
                            fileDialog.Filter = ToolConstants.Configuration.FilterFile.Excel;
                            fileDialog.FileName = gridView.ViewCaption;
                            if (fileDialog.ShowDialog() == DialogResult.OK)
                            {
                                //gridView.BeginUpdate();
                                //gridView.BestFitColumns();
                                //gridView.Columns[1].Visible = false;
                                //gridView.Columns[2].Visible = false;
                                //gridView.Columns[3].Visible = false;
                                gridView.ExportToXlsx(fileDialog.FileName, option);
                                //gridView.Columns[1].Visible = true;
                                //gridView.Columns[2].Visible = true;
                                //gridView.Columns[3].Visible = true;
                                //gridView.EndUpdate();
                                success = true;

                            }

                            if (success && openNow && MessageBox.Show(ToolConstants.Message.QuestionOpenFileExport, ToolConstants.Form.MessageBox.Message, MessageBoxButtons.YesNo) == DialogResult.Yes)
                            {
                                System.Diagnostics.Process process = new System.Diagnostics.Process();
                                process.StartInfo.FileName = fileDialog.FileName;
                                process.StartInfo.Verb = "Open";
                                process.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Normal;
                                process.Start();

                            }

                        }
                        catch (Exception ex)
                        {

                            MessageBox.Show(ex.Message, ToolConstants.Form.MessageBox.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }

                    }
                    else
                    {
                        MessageBox.Show(ToolConstants.Message.NoDataToExport, ToolConstants.Form.MessageBox.Message,
                                        MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    break;

                //1: Export all
                case 1:
                    if (gridView.RowCount > 0)
                    {
                        try
                        {
                            bool success = false;
                            XlsxExportOptions option = new XlsxExportOptions();
                            option.ShowGridLines = true;
                            option.SheetName = gridView.ViewCaption;

                            FileDialog fileDialog = new SaveFileDialog();
                            fileDialog.Filter = ToolConstants.Configuration.FilterFile.Excel;
                            fileDialog.FileName = gridView.ViewCaption;
                            if (fileDialog.ShowDialog() == DialogResult.OK)
                            {
                                gridView.BestFitColumns();
                                gridView.SelectAll();
                                gridView.ExportToXlsx(fileDialog.FileName, option);
                                success = true;
                            }

                            if (success && openNow && MessageBox.Show(ToolConstants.Message.QuestionOpenFileExport, ToolConstants.Form.MessageBox.Message, MessageBoxButtons.YesNo) == DialogResult.Yes)
                            {
                                System.Diagnostics.Process process = new System.Diagnostics.Process();
                                process.StartInfo.FileName = fileDialog.FileName;
                                process.StartInfo.Verb = "Open";
                                process.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Normal;
                                process.Start();

                            }
                        }
                        catch (Exception ex)
                        {

                            MessageBox.Show(ex.Message, ToolConstants.Form.MessageBox.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }

                    }
                    else
                    {
                        MessageBox.Show(ToolConstants.Message.NoDataToExport, ToolConstants.Form.MessageBox.Message,
                                        MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    break;

                default:
                    break;
            }

        }

        public static void ExportToExcelExtraSheet(List<GridControl> listGridView, bool openNow, string name)
        {
            if (listGridView.Count < 1) return;

            var printingSystem = new PrintingSystemBase();
            var compositeLink = new CompositeLinkBase();
            compositeLink.PrintingSystemBase = printingSystem;


            var options = new XlsxExportOptions();
            options.ExportMode = XlsxExportMode.SingleFilePageByPage;
            options.ShowGridLines = true;

            if (listGridView.Count > 0)
            {

                try
                {
                    bool success = false;
                    FileDialog fileDialog = new SaveFileDialog();
                    fileDialog.Filter = ToolConstants.Configuration.FilterFile.Excel;
                    fileDialog.FileName = name;
                    if (fileDialog.ShowDialog() == DialogResult.OK)
                    {
                        Cursor.Current = Cursors.WaitCursor;
                        foreach (GridControl grid in listGridView)
                        {
                            ((GridView)grid.DefaultView).OptionsPrint.PrintSelectedRowsOnly = false;
                            var printingSystem1 = new PrintingSystemBase();
                            var link = new PrintableComponentLinkBase();
                            link.Component = grid;
                            link.PrintingSystemBase = printingSystem1;
                            link.PrintingSystemBase.ExportOptions.Xlsx.SheetName = grid.DefaultView.ViewCaption;
                            link.PrintingSystemBase.ExportOptions.Xls.SheetName = grid.DefaultView.ViewCaption;

                            compositeLink.Links.Add(link);
                        }

                        compositeLink.CreatePageForEachLink();
                        compositeLink.ExportToXlsx(fileDialog.FileName, options);
                        success = true;
                        Cursor.Current = Cursors.Default;

                    }

                    if (success && openNow && MessageBox.Show(ToolConstants.Message.QuestionOpenFileExport, ToolConstants.Form.MessageBox.Message, MessageBoxButtons.YesNo) == DialogResult.Yes)
                    {
                        System.Diagnostics.Process process = new System.Diagnostics.Process();
                        process.StartInfo.FileName = fileDialog.FileName;
                        process.StartInfo.Verb = "Open";
                        process.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Normal;
                        process.Start();

                    }
                }
                catch (Exception ex)
                {

                    MessageBox.Show(ex.Message, ToolConstants.Form.MessageBox.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }

            }
            else
            {
                MessageBox.Show(ToolConstants.Message.NoDataToExport, ToolConstants.Form.MessageBox.Message,
                                MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        public class ComboboxItem
        {
            public string Text { get; set; }
            public object Value { get; set; }

            public override string ToString()
            {
                return Text;
            }
        }

        public class ItemGridColumn
        {
            protected GridColumn column = new GridColumn();
            protected int index;

            public GridColumn Column
            {
                get { return column; }

                set { column = value; }
            }

            public int VisibleIndex
            {
                get { return index; }

                set { index = value; }
            }


        }

        public class ListItem
        {
            public string ID { get; set; }
            public string Value { get; set; }
            public string Note { get; set; }

            public override string ToString()
            {
                return Value;
            }

            public ListItem(string iD, string value, string note = null)
            {
                this.ID = iD;
                this.Value = value;
                this.Note = note;
            }
        }

        public class OptionDataItem
        {
            private string partNo { get; set; }
            private string optionID { get; set; }

            public string PartNo()
            {
                return partNo;
            }

            public string OptionID()
            {
                return optionID;
            }

            public OptionDataItem(string partNo, string optionID)
            {
                this.partNo = partNo;
                this.optionID = optionID;
            }
        }

        public class OptionDataUpdateItem
        {
            private string partNo { get; set; }
            private string optionID { get; set; }
            private string proTime { get; set; }
            private string updateDay { get; set; }
            private string staffID { get; set; }

            public string PartNo()
            {
                return partNo;
            }

            public string OptionID()
            {
                return optionID;
            }

            public string ProTime()
            {
                return proTime;
            }

            public string UpdateDay()
            {
                return updateDay;
            }

            public string StaffID()
            {
                return staffID;
            }

            public OptionDataUpdateItem(string partNo, string optionID, string proTime, string updateDay, string staffId = "")
            {
                this.partNo = partNo;
                this.optionID = optionID;
                this.proTime = proTime;
                this.updateDay = updateDay;
                this.staffID = staffId;
            }
        }

        public static void AdjustWidthComboBox(object sender, EventArgs e)
        {
            System.Windows.Forms.ComboBox senderComboBox = (System.Windows.Forms.ComboBox)sender;
            int width = senderComboBox.DropDownWidth;
            Graphics g = senderComboBox.CreateGraphics();
            Font font = senderComboBox.Font;
            int vertScrollBarWidth =
                (senderComboBox.Items.Count > senderComboBox.MaxDropDownItems)
                ? SystemInformation.VerticalScrollBarWidth : 0;

            int newWidth;
            foreach (object item in ((System.Windows.Forms.ComboBox)sender).Items)
            {
                newWidth = (int)g.MeasureString(item.ToString(), font).Width
                    + vertScrollBarWidth;
                if (width < newWidth)
                {
                    width = newWidth;
                }
            }
            senderComboBox.DropDownWidth = width;
        }

        public static bool IsNumericInt(string str)
        {
            try
            {
                str = str.Trim();
                int foo = int.Parse(str);
                return (true);
            }
            catch (FormatException e)
            {
                return (false);
            }
        }

        public static DataRow[] GetMinDataRow(DataRow[] dataRows, string field, string dataType)
        {
            int i = 0;
            int count = 0;
            DataRow[] result;

            switch (dataType.ToUpper())
            {
                case "DATETIME":
                    DateTime minDate = dataRows[0].Field<DateTime>(field);

                    foreach (DataRow dr in dataRows)
                    {
                        if (DateTime.Compare(minDate, dr.Field<DateTime>(field)) > 0)
                        {
                            minDate = dr.Field<DateTime>(field);
                        }
                    }

                    foreach (DataRow dataRow in dataRows)
                    {
                        if (DateTime.Compare(minDate, dataRow.Field<DateTime>(field)) == 0)
                        {
                            count++;
                        }
                    }

                    result = new DataRow[count];
                    if (count > 0)
                    {
                        foreach (DataRow dataRow in dataRows)
                        {
                            if (DateTime.Compare(minDate, dataRow.Field<DateTime>(field)) == 0)
                            {
                                result[i] = dataRow;
                                i++;
                            }
                        }
                    }
                    break;

                case "FLOAT":
                    double minValue = Math.Round(float.Parse(dataRows[0][field].ToString()), 2);

                    foreach (DataRow dr in dataRows)
                    {
                        if (minValue > Math.Round(float.Parse(dr[field].ToString()), 2))
                        {
                            minValue = Math.Round(float.Parse(dr[field].ToString()), 2);
                        }
                    }

                    foreach (DataRow dataRow in dataRows)
                    {
                        if (Math.Round(float.Parse(dataRow[field].ToString()), 2).ToString().Equals(minValue.ToString()))
                        {
                            count++;
                        }
                    }

                    result = new DataRow[count];
                    if (count > 0)
                    {
                        foreach (DataRow dataRow in dataRows)
                        {
                            if (Math.Round(float.Parse(dataRow[field].ToString()), 2).ToString().Equals(minValue.ToString()))
                            {
                                result[i] = dataRow;
                                i++;
                            }
                        }
                    }
                    break;

                default:
                    result = null;
                    break;
            }



            return result;
        }

    }
}
